package org.jsshbroadcast.xml;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.jsshbroadcast.jsbException.XMLException;
import org.jsshbroadcast.servidor.Servidor;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 *
 * @author Eduardo Folly
 */
public class JDomXml {

    private String localxml;

    public JDomXml(String local) {
        localxml = local;
    }

    public ArrayList<Servidor> lerServidores() throws Exception {
        ArrayList servidores = new ArrayList();

        SAXBuilder sb = new SAXBuilder();

        Document d = sb.build(new File(localxml).toURI().toString());

        Element raiz = d.getRootElement();

        if (raiz.getName().equals("raiz")) {
            List<Element> lista = raiz.getChildren();
            try {
                for (Element e : lista) {
                    String endereco = e.getChildText("endereco");
                    Integer porta = new Integer(e.getChildText("porta"));
                    String usuario = e.getChildText("usuario");
                    boolean senha = new Boolean(e.getChildText("senha"));
                    String mac = e.getChildText("mac");
                    String broadcast = e.getChildText("broadcast");
                    Servidor serv = new Servidor(endereco, porta, usuario, senha, mac, broadcast);

                    servidores.add(serv);
                }
            } catch (Exception e) {
                throw new XMLException(e.getMessage());
            }
        } else {
            throw new XMLException("Elemento raiz inválido.");
        }
        return servidores;
    }
}
